package com.xagent.engine.context;

import com.xagent.core.Properties;
import com.xagent.engine.config.Config;
import com.xagent.engine.context.inter.Context;
import com.xagent.engine.context.inter.InstWrapper;
import com.xagent.engine.plugins.Plugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.instrument.Instrumentation;

public class AgentContext implements Context {

    private final InstWrapper instWrapper;
    private static Context instance;
    /**
     * 配置实现类
     */
    private final Config configImpl;
    private Plugin[] plugins;
    private static final Logger agentLogger = LoggerFactory.getLogger(Properties.COMMON_LOGGER_AGENT);
    private static final Logger securityLogger = LoggerFactory.getLogger(Properties.COMMON_LOGGER_SECURITY);


    private AgentContext(Config config, Instrumentation instrumentation) {
        configImpl = config;
        this.instWrapper = new InstWrapperImpl(instrumentation);
    }

    public static void createContext(Config config, Instrumentation instrumentation) {
        if (instance == null) {
            instance = new AgentContext(config, instrumentation);
        }
    }

    public static Context getContext() {
        if (instance == null) throw new NullPointerException("no AgentContext was found.");
        return instance;
    }

    @Override
    public Config getConfig() {
        return configImpl;
    }

    @Override
    public InstWrapper getInstWrapper() {
        return instWrapper;
    }

    @Override
    public void setPlugins(Plugin[] plugins) {
        this.plugins = plugins;
    }

    @Override
    public Plugin[] getPlugins() {
        return plugins;
    }

    @Override
    public Logger getAgentLogger() {
        return agentLogger;
    }

    @Override
    public Logger getSecurityLogger() {
        return securityLogger;
    }

    /**
     * @return true则说明是debug模式，否则不是
     */
    @Override
    public boolean isDebug() {
        return "true".equals(System.getProperty(Properties.XAGENT_DEBUG_MODE));
    }
}
